package com.skypan.myapplication.nfc;

import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;

import com.skypan.myapplication.LocalDataApplication;
import com.skypan.myapplication.R;
import com.skypan.myapplication.bean.LoginR;
import com.skypan.myapplication.bean.WriteListR;
import com.skypan.myapplication.bean.WriteR;
import com.skypan.myapplication.http.WriteCallback;
import com.skypan.myapplication.http.WriteListCallback;
import com.zhy.http.okhttp.OkHttpUtils;

import java.nio.charset.Charset;
import java.util.Calendar;
import java.util.Locale;

import okhttp3.Call;


/**
 * Created by gc on 2016/12/8.
 */
public class WriteTextActivity extends BaseNfcActivity {

    Calendar calendar = Calendar.getInstance();
    String year = String.valueOf(calendar.get(Calendar.YEAR));
    String month = String.valueOf(calendar.get(Calendar.MONTH)+1);
    String day = String.valueOf(calendar.get(Calendar.DAY_OF_MONTH));
    String hour = String.valueOf(calendar.get(Calendar.HOUR_OF_DAY));
    String minute = String.valueOf(calendar.get(Calendar.MINUTE));
    String second = String.valueOf(calendar.get(Calendar.SECOND));
    String time = year + "-" + month + "-" + day + " "+ hour + ":" + minute + ":" + second;


    private String mText = "数据错误";
    private String productText;
    private String get_url = "http://39.105.165.31:8080/product/queryOne";//生产操作人员获取
    private String TH_url = "http://39.105.165.31:8080/product/query";//物流医院获取
    private String post_url = "http://39.105.165.31:8080/product/update";//更新数据库
    LoginR localuser = LocalDataApplication.getInstance().getLocalResponse();



    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_write_text);

    }

    @Override
    public void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (mText == null)
            return;
        //获取Tag对象
        Tag detectedTag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
        byte[] tagbytes = detectedTag.getId();    //NFC的ID转16进制字符串
        String mTagId = bytesToHexString(tagbytes);

        postWrite(mTagId,detectedTag);//写入/更新数据库
    }
    /**
     * 创建NDEF文本数据
     *
     * @param text
     * @return
     */
    public static NdefRecord createTextRecord(String text) {
        byte[] langBytes = Locale.CHINA.getLanguage().getBytes(Charset.forName("US-ASCII"));
        Charset utfEncoding = Charset.forName("UTF-8");
        //将文本转换为UTF-8格式
        byte[] textBytes = text.getBytes(utfEncoding);
        //设置状态字节编码最高位数为0
        int utfBit = 0;
        //定义状态字节
        char status = (char) (utfBit + langBytes.length);
        byte[] data = new byte[1 + langBytes.length + textBytes.length];
        //设置第一个状态字节，先将状态码转换成字节
        data[0] = (byte) status;
        //设置语言编码，使用数组拷贝方法，从0开始拷贝到data中，拷贝到data的1到langBytes.length的位置
        System.arraycopy(langBytes, 0, data, 1, langBytes.length);
        //设置文本字节，使用数组拷贝方法，从0开始拷贝到data中，拷贝到data的1 + langBytes.length
        //到textBytes.length的位置
        System.arraycopy(textBytes, 0, data, 1 + langBytes.length, textBytes.length);
        //通过字节传入NdefRecord对象
        //NdefRecord.RTD_TEXT：传入类型 读写
        NdefRecord ndefRecord = new NdefRecord(NdefRecord.TNF_WELL_KNOWN,
                NdefRecord.RTD_TEXT, new byte[0], data);
        return ndefRecord;
    }

    /**
     * 写数据
     *
     * @param ndefMessage 创建好的NDEF文本数据
     * @param tag         标签
     * @return
     */
    public static boolean writeTag(NdefMessage ndefMessage, Tag tag) {
        try {
            Ndef ndef = Ndef.get(tag);
            ndef.connect();
            ndef.writeNdefMessage(ndefMessage);
            return true;
        } catch (Exception e) {
        }
        return false;
    }



    public void postWrite(final String mTagId, final Tag detectedTag)
    {
        if(localuser.data.userIdentity.equals("3")){//生产操作人员写入发送
            OkHttpUtils
                    .get()//
                    .url(get_url)//
                    .addParams("id",localuser.data.companyId)//
                    .build()//
                    .execute(new WriteCallback()
                    {
                        @Override
                        public void onError(Call call, Exception e, int id)
                        {
                            Toast.makeText(WriteTextActivity.this,e.getMessage(),Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(WriteR response, int id)
                        {
                            postManufactureWrite(response,post_url,mTagId);
                            mText = "产品ID：" + response.data.productId + "\n"+
                                        "产品名称：" + response.data.productName + "\n"+
                                        "产品简介：" + response.data.productIntroduce + "\n"+
                                        "生产日期：" + response.data.productDate + "\n"+
                                        "保质期：" + response.data.productPeriod + "\n"+
                                        "生产公司ID：" + response.data.manufacturerId + "\n"+
                                        "生产批次：" + response.data.productBatch + "\n"+
                                        "产品状态：" + "可用" + "\n"+
                                        "物流公司ID：" + response.data.transporterId + "\n"+
                                        "物流时间：" + response.data.productTdate + "\n"+
                                        "接收商ID：" + response.data.hospitalId + "\n"+
                                        "接收时间：" + response.data.productHdate + "\n";


                            NdefMessage ndefMessage = new NdefMessage(
                                    new NdefRecord[]{createTextRecord(mText)});
                            boolean result = writeTag(ndefMessage,  detectedTag);
                            if (result) {
                                Toast.makeText(WriteTextActivity.this, "写入成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(WriteTextActivity.this, "写入失败", Toast.LENGTH_SHORT).show();
                            }


                        }
                    });
        }

        else if(localuser.data.userIdentity.equals("4")){//物流写入/发送
            OkHttpUtils
                    .get()//
                    .url(TH_url)//
                    .addParams("tagId",mTagId)//
                    .build()//
                    .execute(new WriteListCallback()
                    {
                        @Override
                        public void onError(Call call, Exception e, int id)
                        {
                            Toast.makeText(WriteTextActivity.this,"接收错误"+e.getMessage(),Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(WriteListR response, int id) {

                            postTransferorWrite(response,post_url);
                            mText = "产品ID：" + response.data.getList().get(0).productId + "\n"+
                                    "产品名称：" + response.data.getList().get(0).productName + "\n"+
                                    "产品简介：" + response.data.getList().get(0).productIntroduce + "\n"+
                                    "生产日期：" + response.data.getList().get(0).productDate + "\n"+
                                    "保质期：" + response.data.getList().get(0).productPeriod + "\n"+
                                    "生产公司ID：" + response.data.getList().get(0).manufacturerId + "\n"+
                                    "生产批次：" + response.data.getList().get(0).productBatch + "\n"+
                                    "产品状态：" + "可用" + "\n"+
                                    "物流公司ID：" + localuser.data.companyId + "\n"+
                                    "物流时间：" + time + "\n"+
                                    "接收商ID：" + response.data.getList().get(0).hospitalId + "\n"+
                                    "接收时间：" + response.data.getList().get(0).productHdate + "\n";


                            NdefMessage ndefMessage = new NdefMessage(
                                    new NdefRecord[]{createTextRecord(mText)});
                            boolean result = writeTag(ndefMessage,  detectedTag);
                            if (result) {
                                Toast.makeText(WriteTextActivity.this, "写入成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(WriteTextActivity.this, "写入失败", Toast.LENGTH_SHORT).show();
                            }

                        }
                    });
        }
        else {//医院接受写入/发送
            OkHttpUtils
                    .get()//
                    .url(TH_url)//
                    .addParams("tagId",mTagId)//
                    .build()//
                    .execute(new WriteListCallback()
                    {
                        @Override
                        public void onError(Call call, Exception e, int id)
                        {
                            Toast.makeText(WriteTextActivity.this,"接收"+ e.getMessage(),Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onResponse(WriteListR response, int id)
                        {
                            postHospitalWrite(response,post_url);
                            mText = "产品ID：" + response.data.getList().get(0).productId + "\n"+
                                    "产品名称：" + response.data.getList().get(0).productName + "\n"+
                                    "产品简介：" + response.data.getList().get(0).productIntroduce + "\n"+
                                    "生产日期：" + response.data.getList().get(0).productDate + "\n"+
                                    "保质期：" + response.data.getList().get(0).productPeriod + "\n"+
                                    "生产公司ID：" + response.data.getList().get(0).manufacturerId + "\n"+
                                    "生产批次：" + response.data.getList().get(0).productBatch + "\n"+
                                    "产品状态：" + "可用" + "\n"+
                                    "物流公司ID：" + response.data.getList().get(0).transporterId + "\n"+
                                    "物流时间：" + response.data.getList().get(0).productTdate + "\n"+
                                    "接收商ID：" + localuser.data.companyId + "\n"+
                                    "接收时间：" + time + "\n";


                            NdefMessage ndefMessage = new NdefMessage(
                                    new NdefRecord[]{createTextRecord(mText)});
                            boolean result = writeTag(ndefMessage,  detectedTag);
                            if (result) {
                                Toast.makeText(WriteTextActivity.this, "写入成功", Toast.LENGTH_SHORT).show();
                            } else {
                                Toast.makeText(WriteTextActivity.this, "写入失败", Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
        }

    }

    public void postManufactureWrite(WriteR product, String url,String mTagId) {//生产操作人员更新数据库

        OkHttpUtils
                .post()//
                .url(url)//
                .addParams("productId", product.data.productId)//
                .addParams("tagId",mTagId)//
                .addParams("productStatus","1")//
                .build()//
                .execute(new WriteCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(WriteTextActivity.this,"发送"+e.getMessage(),Toast.LENGTH_SHORT).show();
                    }

                    public void onResponse(WriteR response, int id) {
                    }
                });
    }

    public void postTransferorWrite(WriteListR product, String url) {//物流更新数据库

        OkHttpUtils
                .post()//
                .url(url)//
                .addParams("productId", product.getData().getList().get(0).productId)//
                .addParams("transporterId",localuser.data.companyId)
                .addParams("productTdate",time)//


                .build()//
                .execute(new WriteListCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(WriteTextActivity.this,"发送"+e.getMessage(),Toast.LENGTH_SHORT).show();
                    }

                    public void onResponse(WriteListR response, int id) {
                    }
                });
    }

    public void postHospitalWrite(WriteListR product, String url) {//医院接受更新数据库

        OkHttpUtils
                .post()//
                .url(url)//
                .addParams("productId", product.data.getList().get(0).productId)//
                .addParams("hospitalId",localuser.data.companyId)
                .addParams("productHdate",time)//

                .build()
                .execute(new WriteCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        Toast.makeText(WriteTextActivity.this,"发送"+e.getMessage(),Toast.LENGTH_SHORT).show();
                    }

                    public void onResponse(WriteR response, int id) {
                    }
                });
    }


    private String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder();

        if (src == null || src.length <= 0) {
            return null;
        }
        char[] buffer = new char[2];
        for (int i = 0; i < src.length; i++) {
            buffer[0] = Character.toUpperCase(Character.forDigit(
                    (src[i] >>> 4) & 0x0F, 16));
            buffer[1] = Character.toUpperCase(Character.forDigit(src[i] & 0x0F,
                    16));
            System.out.println(buffer);
            stringBuilder.append(buffer);
        }
        return stringBuilder.toString();
    }
}
